import {encrypt} from './sm4Util'
import md5 from 'md5'

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]'
}

function paramsSort(params) {
  var arr = [];
  var keyArr = [];
  for (var i in params) {
    keyArr.push(i)
  }
  if (!isArray(params)) {
    keyArr.sort()
  }
  for (var i in keyArr) {
    var key = keyArr[i];
    var val = params[key];
    if (typeof val == "object") {
      if (val !== null) {
        arr.push(key + "=" + paramsSort(val));
      }
    } else {
      if (val !== undefined) {
        arr.push(key + "=" + val);
      }
    }
  }
  var str = arr.join("&");
  console.log(str)
  return str;
}

export default function paramsSign(params) {
  var signText = 'timestamp='+Date.now()+'&signature='+md5(paramsSort(params))
  console.log(signText)
  return encrypt(signText)
}
